﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace BeerManagementSystem
{
    internal class GameCountdown
    {
        public event EventHandler GameCdStart;
        public event EventHandler<GameCdEventArgs> GameCdDrink;

        private static GameCountdown _instance;

        public static GameCountdown Instance
        {
            get { return _instance ?? (_instance = new GameCountdown()); }
        }


        private DispatcherTimer _initiateTimer;
        private DispatcherTimer _initiateGameTimer;
        private Random rd;
        private int _playerID;
        private List<int> _userList;
        
        private GameCountdown()
        {
            _userList = new List<int>();
            rd = new Random();
            _initiateTimer = new DispatcherTimer();
            _initiateGameTimer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(Properties.Settings.Default.GameCdStartIntervall)};
            _initiateGameTimer.Tick += InitiateGameTimerOnTick;
            _initiateTimer.Tick += InitiateTimerOnTick;
            InitiateNewGame();
        }

        public List<int> GetCdGamePlayingList()
        {
            return _userList;
        } 
        
        private void InitiateTimerOnTick(object sender, EventArgs eventArgs)
        {
            Random rnd = new Random();
            _playerID = _userList.ElementAt(rnd.Next(_userList.Count));
            _initiateTimer.Stop();
            _initiateGameTimer.Start();
            GameCdStart(this, null);
        }

        private void InitiateGameTimerOnTick(object sender, EventArgs eventArgs)
        {
            _initiateGameTimer.Stop();
            GameCdDrink(this, new GameCdEventArgs(_playerID));
        }

        public void AddToList(int id)
        {
            if (!_userList.Contains(id)) _userList.Add(id);
        }

        public void RemoveFromList(int id)
        {
            if (_userList.Contains(id)) _userList.Remove(_userList.Find(i => i == id));
        }

        public void InitiateNewGame()
        {
            int number = rd.Next(1, Properties.Settings.Default.GameCdInterval);
            _initiateTimer.Interval = TimeSpan.FromMinutes(number);
            _initiateTimer.Start();

        }
    }
}
